package com.my.lucky.controller;

import cn.hutool.core.util.StrUtil;
import com.my.lucky.config.IwencaiConfig;
import com.my.lucky.dto.StockAnalysisResult;
import com.my.lucky.service.StockAnalysisService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.time.DayOfWeek;
import java.time.LocalDate;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 股票数据分析控制器
 * 用于展示股票选出后的价格表现分析
 */
@Slf4j
@Controller
@RequestMapping("/analysis")
public class StockAnalysisController {

    @Autowired
    private StockAnalysisService stockAnalysisService;

    @Autowired
    private IwencaiConfig iwencaiConfig;

    public static Map<String, Long> countConcepts(List<StockAnalysisResult> pageContent) {
        if (pageContent == null) {
            return Collections.emptyMap();
        }

        return pageContent.stream()
                .filter(Objects::nonNull)
                .map(result -> {
//                    String concept = result.getConcept() != null ? result.getConcept() : "";
                    String allConcept = result.getAllconcept() != null ? result.getAllconcept() : "";
//                    return concept + "," + allConcept;
                    return allConcept;
                })
                .filter(str -> !str.isEmpty())
                .flatMap(str -> Arrays.stream(str.split(",")))
                .filter(concept -> !concept.trim().isEmpty())
                .collect(Collectors.groupingBy(
                        String::trim,
                        Collectors.counting()
                ));
    }

    public static String getSortedConceptCounts(List<StockAnalysisResult> pageContent) {
        Map<String, Long> conceptCounts = countConcepts(pageContent);

        // 按Value降序排序
        List<Map.Entry<String, Long>> sortedEntries = conceptCounts.entrySet().stream()
                .sorted(Map.Entry.<String, Long>comparingByValue().reversed())
                .collect(Collectors.toList());
        // 格式化输出
        StringBuilder sb = new StringBuilder();
        for (Map.Entry<String, Long> entry : sortedEntries) {
            if (entry.getValue() > 1) {
                sb.append(entry.getKey())
                        .append("[")
                        .append(entry.getValue())
                        .append("]")
                        .append(";");
            }
        }
        return sb.toString();
    }

    /**
     * 分析页面
     */
    @GetMapping
    public String analysisPage(Model model) {
        // 设置默认查询条件：当天
        LocalDate today = LocalDate.now();
//        LocalDate threeDaysAgo = LocalDate.now().minusDays(1);
        LocalDate yesterday = LocalDate.now().minusDays(1);//默认取2天数据
        if (today.getDayOfWeek() == DayOfWeek.MONDAY) {//周一取到周五的数据
            yesterday = today.with(DayOfWeek.FRIDAY).minusWeeks(1);
        } else if (today.getDayOfWeek() == DayOfWeek.SATURDAY || today.getDayOfWeek() == DayOfWeek.SUNDAY) {
            yesterday = today.with(DayOfWeek.THURSDAY);//周末取到周四周五的数据
        }
//      LocalDate startDate = today;
        LocalDate endDate = today;

        model.addAttribute("startDate", yesterday);
        model.addAttribute("endDate", endDate);

        return "analysis";
    }

    /**
     * 获取股票分析数据的API接口（支持分页）
     */
    @GetMapping("/data")
    @ResponseBody
    public Map<String, Object> getAnalysisData(
            @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate startDate,
            @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate endDate,
            @RequestParam(required = false) String timeFilter,
            @RequestParam(required = false) Integer type,
            @RequestParam(required = false) Integer conceptFlow,
            @RequestParam(required = false) String market,
            @RequestParam(required = false) String stockSearch,
            @RequestParam(required = false) String conceptSearch,
            @RequestParam(required = false) String wencaiKeySearch,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "20") int size,
            @RequestParam(required = false) String sortField,
            @RequestParam(required = false) String sortDirection) {
        Map<String, Object> response = new HashMap<>();
        try {
            // 获取分页分析结果
            Page<StockAnalysisResult> pageResult = stockAnalysisService.getStockAnalysisResultsWithPagination(startDate, endDate, timeFilter, type, market, stockSearch, conceptSearch, page, size, sortField, sortDirection);

            // 获取统计信息（基于所有数据，不分页）
            List<StockAnalysisResult> allResults = stockAnalysisService.getStockAnalysisResults(startDate, endDate, timeFilter, type, market, stockSearch, conceptSearch);

            if (StrUtil.isNotBlank(wencaiKeySearch)) {
                List<StockAnalysisResult> hasKey = new ArrayList<>();
                for (StockAnalysisResult record : allResults) {
                    try {
                        // 应用股票代码/名称搜索筛选
                        if (wencaiKeySearch != null && !wencaiKeySearch.trim().isEmpty()) {
                            String searchTerm = wencaiKeySearch.trim().toLowerCase();
                            String keyword = record.getKeyword() != null ? record.getStockCode().toLowerCase() : "";
                            // 如果股票代码或名称都不包含搜索词，则跳过
                            if (keyword.contains(searchTerm)) {
//                                continue;
//                            }else{
                                hasKey.add(record);
                            }
                        }
                    } catch (Exception e) {
                        log.error("分析股票 {} 时出错: {}", record.getStockCode(), e.getMessage());
                    }
                }
                if (hasKey != null && hasKey.size() > 0) {
                    allResults = hasKey;
                }
            }

            StockAnalysisService.StockAnalysisStatistics statistics = stockAnalysisService.getStatistics(allResults);

            //板块汇总
            List<StockAnalysisResult> pageContent = pageResult.getContent();
            if (StrUtil.isNotBlank(wencaiKeySearch) && pageContent != null) {
                List<StockAnalysisResult> has = new ArrayList<>();
                for (StockAnalysisResult record : pageContent) {
                    try {
                        // 应用股票代码/名称搜索筛选
                        if (wencaiKeySearch != null && !wencaiKeySearch.trim().isEmpty()) {
                            String searchTerm = wencaiKeySearch.trim().toLowerCase();
                            String keyword = record.getKeyword() != null ? record.getStockCode().toLowerCase() : "";
                            // 如果股票代码或名称都不包含搜索词，则跳过
                            if (keyword.contains(searchTerm)) {
                                has.add(record);
                            }
                        }
                    } catch (Exception e) {
                        log.error("分析股票 {} 时出错: {}", record.getStockCode(), e.getMessage());
                    }
                }
                if (has != null && has.size() > 0) {
                    pageContent = has;
                }
            }

            response.put("success", true);
            response.put("data", pageContent);
            response.put("flowStock", iwencaiConfig.getFocus());
            response.put("allOptional", iwencaiConfig.getAllOptional());
            response.put("flowGainian", iwencaiConfig.getFocusGaiNian());

            String formattedCounts = getSortedConceptCounts(pageContent);
//            System.out.println(formattedCounts);
            response.put("conceptCount", formattedCounts);

            response.put("statistics", statistics);

            // 构建分页信息
            Map<String, Object> pagination = new HashMap<>();
            pagination.put("currentPage", pageResult.getNumber());
            pagination.put("totalPages", pageResult.getTotalPages());
            pagination.put("totalElements", pageResult.getTotalElements());
            pagination.put("size", pageResult.getSize());
            pagination.put("hasNext", pageResult.hasNext());
            pagination.put("hasPrevious", pageResult.hasPrevious());
            response.put("pagination", pagination);

            response.put("message", "查询成功");

//            System.out.println(response);
        } catch (Exception e) {
            log.error("获取股票分析数据失败", e);
            response.put("success", false);
            response.put("message", "查询失败：" + e.getMessage());
        }

        return response;
    }

    /**
     * 导出分析数据（可选功能）
     */
    @GetMapping("/export")
    @ResponseBody
    public Map<String, Object> exportAnalysisData(
            @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate startDate,
            @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate endDate,
            @RequestParam(required = false) String timeFilter,
            @RequestParam(required = false) Integer type,
            @RequestParam(required = false) String market,
            @RequestParam(required = false) String stockSearch,
            @RequestParam(required = false) String conceptSearch) {

        Map<String, Object> response = new HashMap<>();

        try {
            List<StockAnalysisResult> results = stockAnalysisService.getStockAnalysisResults(startDate, endDate, timeFilter, type, market, stockSearch, conceptSearch);

            // 这里可以添加导出逻辑，比如生成Excel文件
            // 目前只返回数据

            String res = results.stream()
                    .map(StockAnalysisResult::getStockCode) // 替换为你要获取的属性方法
                    .collect(Collectors.joining(","));
            response.put("data", res);

//            response.put("success", true);
//            response.put("data", results);
//            response.put("message", "导出成功");

        } catch (Exception e) {
            log.error("导出股票分析数据失败", e);
            response.put("success", false);
            response.put("message", "导出失败：" + e.getMessage());
        }

        return response;
    }


} 